<?php
namespace Modules\News\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Services\WechatService;
use Illuminate\Http\Request;
use Modules\News\Entities\NewsReply;
use Modules\News\Http\Requests\NewsReplyRequest;
use Modules\Wx\Entities\WxRule;

class NewsReplyController extends Controller
{
    //显示列表
    public function index()
    {
        $data = NewsReply::paginate(10);
        return view('news::news_reply.index', compact('data'));
    }

    //创建视图
    public function create(NewsReply $news_reply,WechatService $wechatService)
    {
        $view = $wechatService->ruleView();
        return view('news::news_reply.create',compact('news_reply','view'));
    }

    //保存数据
    public function store(NewsReplyRequest $request,NewsReply $news_reply,WechatService $wechatService)
    {
        //将规则数据和关键词数据调用服务类方法进行保存
        $rule = $wechatService->saveRule();
        //将图文回复的消息存入图文表
        NewsReply::create([
            'data' => $request->input('data'),
            'rule_id' => $rule['id'],
        ]);
        return redirect('/news/news_reply')->with('success', '保存成功');
    }

    //显示记录
    public function show(NewsReply $field)
    {
        return view('news::news_reply.show', compact('field'));
    }

    //编辑视图
    public function edit(NewsReply $news_reply,WechatService $wechatService)
    {
//        $view = $wechatService->ruleView($news_reply['rule_id']);
        $view = $wechatService->ruleView($news_reply['rule_id']);
        return view('news::news_reply.edit', compact('news_reply','view'));
    }

    //更新数据
    public function update(NewsReplyRequest $request, NewsReply $news_reply,WechatService $wechatService)
    {
        //将规则数据和关键词数据调用服务类方法进行保存
        $rule = $wechatService->saveRule($news_reply['rule_id']);
        //对图文回复数据进行编辑
        $news_reply->data = $request->input('data');
        $news_reply->rule_id = $rule['id'];
        $news_reply->save();
        return redirect('/news/news_reply')->with('success','更新成功');
    }

    //删除模型
    public function destroy(NewsReply $news_reply)
    {
        //删除对应规则数据
        WxRule::destroy($news_reply['rule_id']);
        $news_reply->delete();
        return redirect('news/news_reply')->with('success','删除成功');
    }
}
